<template>
  <div class="api">
    <!--搜索区域-->
    <el-row>
      <el-col :span="22">
        <span style="font-size: 14px;font-weight: 600">账户名称: &nbsp;</span>
        <el-input v-model="params.account" style="width: 160px" placeholder="请输入账户名称" clearable></el-input>
        <span class="so" style="font-size: 14px;font-weight: 600">账户呢称: &nbsp;</span>
        <el-input v-model="params.name" style="width: 160px" placeholder="请输入账户呢称" clearable></el-input>
        <span class="so">部门: &nbsp;</span>
        <el-cascader
          @change="change"
          v-model="test"
          style="width: 160px"
          :options="deptTree"
          :props="{ checkStrictly: true ,children: 'children',label:'deptName',value:'id'}"
          clearable></el-cascader>
      </el-col>
      <!--查询按钮-->
      <el-col :span="2" >
        <el-button type="primary" plain style="width: 6vw" icon="Search" @click="getDataList()">查询</el-button>
      </el-col>
    </el-row>
    <!--操作区域-->
    <el-row style="margin-top: 25px">
      <el-col :span="24">
        <el-button type="primary" plain icon="Plus" @click="drawerAdd" v-if="buttonPermissions('user:add')">新增</el-button>
        <el-button type="success" plain icon="Download" @click="exportExcel()" v-if="buttonPermissions('user:export')">导出</el-button>
        <el-button type="danger" plain icon="DeleteFilled" @click="dataDeleteList()" v-if="buttonPermissions('user:delete')">删除</el-button>
      </el-col>
    </el-row>
    <!--表格区域-->
    <el-row style="margin-top: 25px">
      <el-col :span="24">
        <el-table
          @selection-change="handleSelectionChange"
          :data="tableData" style="width: 100%"
          :header-cell-style="{'background-color':'#F2F6FC'}" empty-text="暂无数据">
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column prop="account" label="账户"> </el-table-column>
          <el-table-column prop="name" label="呢称"> </el-table-column>
          <el-table-column prop="avatar" label="头像" >
          <template  #default="scope">
            <el-avatar :size="51" :src="scope.row.avatar" @click="avatarUpdate.dialogFormAvatar = true;avatarUpdate.avatarEntity = scope.row" />
          </template>
          </el-table-column>
          <el-table-column prop="phone" label="手机号" width="120"> </el-table-column>
          <el-table-column prop="deptNameList" label="部门" align="center">
            <template  #default="scope">
              <span v-for="(item,index)  in scope.row.deptNameList" :key="index" style="margin-left: 2px">
                <el-tag >{{item}}</el-tag>
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="postNameList" label="岗位" align="center">
            <template  #default="scope">
              <span v-for="(item,index)  in scope.row.postNameList" :key="index" style="margin-left: 2px">
                <el-tag>{{item}}</el-tag>
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="ruleNameList" label="角色" width="220px" align="center">
            <template  #default="scope">
              <span v-for="(item,index)  in scope.row.ruleNameList" :key="index" style="margin-left: 4px">
                <el-tag >{{item}}</el-tag>
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" align="center">
            <template  #default="scope">
              <el-tag :type="scope.row.status === 1 ? '':'danger'">{{scope.row.status === 1 ? '启用' : '停用'}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="240">
            <template #default="scope">
              <el-button @click="drawerUpdate(scope.row)" type="text" icon="edit" :disabled="scope.row.account=== 'admin'" v-if="buttonPermissions('user:update')">编辑</el-button>
              <el-button @click="form.id = scope.row.id;dialogFormPassword = true" type="text" icon="Key" style="color: darkseagreen"  v-if="buttonPermissions('user:password')">重置密码</el-button>
              <el-popconfirm title="确认删除该项数据吗？" @confirm="dataDelete(scope.row.id)" v-if="buttonPermissions('user:delete')">
                <template #reference>
                  <el-button
                    :disabled="scope.row.account=== 'admin'"
                    icon="DeleteFilled"
                    style="color: red"
                    type="text">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <el-row style="margin-top: 15px" justify="end">
      <el-col >
        <el-pagination
          background
          style="float: right"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="params.current"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="params.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </el-col>
    </el-row>
    <!--侧边抽屉-->
    <el-drawer :title="drawer.title" v-model="drawer.enable"  destroy-on-close>
      <data-add  @tao="subassembly" v-if="drawer.add"></data-add>
      <data-details v-if="drawer.details" :props-data="drawer.data"></data-details>
      <data-update @tao="subassembly" v-if="drawer.update" :props-data="drawer.data" :dept-tree="tableData"></data-update>
    </el-drawer>
    <!--重置密码-->
    <el-dialog title="重置密码" v-model="dialogFormPassword" width="30%">
      <el-form :model="form" v-loading="loading" :rules="rules" ref="ruleForm">
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="form.newPassword"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormPassword = false;this.form.id = 1">取 消</el-button>
          <el-button type="primary" @click="resetPassword('ruleForm')">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <!--头像上传-->
    <el-dialog title="头像上传" v-model="avatarUpdate.dialogFormAvatar" center width="30%">
      <el-upload
        style="margin-left: 26%"
        action=""
        :show-file-list="false"
        :http-request="avatarRequest"
        :before-upload="beforeAvatarUpload">
        <img :src="avatarUpdate.avatarEntity.avatar" alt="" v-if="avatarUpdate.avatarEntity.avatar !== null" style="width: 210px">
        <Icon name="Plus" :size="100" v-if="avatarUpdate.avatarEntity.avatar === null"></Icon>
      </el-upload>
      <br>
    </el-dialog>
  </div>
</template>

<script>
import DataAdd from '@/components/user/DataAdd'
import DataDetails from '@/components/user/DataDetails'
import DataUpdate from '@/components/user/DataUpdate'
import { ElMessage } from 'element-plus'
import Icon from '@/components/Icon'
import {browserUa} from '@/utils/utils'
export default {
  name: 'Index',
  components:{
    Icon,
    DataUpdate,
    DataDetails,
    DataAdd
  },
  data () {
    return {
      params: {
        current: 1,
        size: 10,
        roleName: '',
        roleAlias: ''
      },
      test:null,
      browser:{},
      form:{
        id:'',
        newPassword:''
      },
      loading:false,
      avatarUpdate:{
        dialogFormAvatar:false,
        avatarEntity:{}
      },
      dialogFormPassword:false,
      drawer:{
        title:'',
        enable:false,
        add:false,
        details:false,
        update:false,
        data:null
      },
      rules:{
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' }
        ],
      },
      deptTree:[],
      total:0,
      tableData: [],
      selectId: []
    }
  },
  computed:{
    //本页面按钮集合,表示该用户在该页面拥有的按钮
    buttonList(){
      let buttonList = this.$store.getters.buttonList
      //过滤获得当前页面配置
      let filter = buttonList.filter(data => data.path === this.$route.path)
      //获得实际按钮
      let buttons = filter.length === 0 ? null : filter[0].children
      if (buttons === null){
        return null
      }
      //获得按钮权限标记
      return buttons.map(data => data.permissionId)
    }
  },
  mounted () {
    this.getDataList()
    this.browser = browserUa()
    this.getDeptTree()
  },
  methods:{
    //按钮权限判断
    buttonPermissions(buttonTag){
      return  this.buttonList === null ? false :this.buttonList.indexOf(buttonTag) >= 0
    },
    //获得页面数据
    getDataList(){
      this.$http.get('/api/user',{params:this.params}).then(res =>{
        this.tableData = res.data.data.records
        this.total = res.data.data.total
      })
    },
    //头像验证
    beforeAvatarUpload(file) {
      const isJPG = (file.type === 'image/jpeg' ||  file.type === 'image/gif' ||  file.type === 'image/png')
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG/GIG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    //头像上传
    avatarRequest(data){
      let formData = new FormData()
      formData.append("id",this.avatarUpdate.avatarEntity.id)
      formData.append("file",data.file)
      this.$http.post('/api/user/avatarUpdate',formData,{headers:{'contentType': 'application/x-www-form-urlencoded'}}).then(res =>{
        ElMessage({
          type: 'success',
          message: res.data.message,
        })
        this.avatarUpdate.dialogFormAvatar = false
      })
    },
    //获得部门数据
    getDeptTree(){
      this.$http.get('/api/dept/tree').then(res =>{
        this.deptTree = res.data.data
      })
    },
    //部门类型级联选择器，获取的的全路径
    change(val){
      if (val !== null && val.length !== 0){
        //拼接路径
        this.params.deptId = val[val.length - 1]
      }else {
        this.params.deptId = null
      }
    },
    //表格数据选中
    handleSelectionChange(val){
     this.selectId = val.map(data => data.id)
    },
    // 批量数据删除
    dataDeleteList(){
      if (this.selectId.length === 0){
        ElMessage.error('请至少选中一项数据')
      }
      //转成逗号分割的字符串
      this.dataDelete( this.selectId.reduce(((previousValue, currentValue) => previousValue + "," + currentValue)))
    },
    // excel导出
    exportExcel(){
     this.$http.get('/api/user/importExcel',{responseType:'blob'}).then(res =>{
       //获取生成设置好的文件名
       let filename = res.headers["content-disposition"].split("=")[1]
       if (filename){
         //文件名解码
         filename = decodeURIComponent(filename);
         //创建blob对象
         const blob = new Blob([res.data]);
         //创建a标签
         let link = document.createElement("a");
         let url = URL.createObjectURL(blob);
         link.style.display = "none";
         link.href = url;
         link.setAttribute("download", filename);
         document.body.appendChild(link);
         link.click();
         //释放资源
         window.URL.revokeObjectURL(url);
         document.body.removeChild(link);
       }
     })
    },
    // 单条数据删除
    dataDelete(id){
      this.$http.delete('/api/user/delete?idList='+id).then(res =>{
        ElMessage({
          type: 'success',
          message: res.data.message,
        })
        this.getDataList()
      })
    },
    //重置密码
    resetPassword(formName){
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //表单提交
          let formData = new FormData()
          formData.append('id',this.form.id)
          formData.append('newPassword',this.form.newPassword)
          this.loading = true
          this.$http.post('/api/user/resetPassword',formData,{headers:{'contentType': 'application/x-www-form-urlencoded'}}).then(res =>{
            ElMessage({
              type: 'success',
              showClose: true,
              message: res.data.message,
            })
            //取消弹窗
            this.dialogFormPassword = false
            this.loading = false
            //刷新数据
            this.getDataList()
          }).catch(() => this.loading = false)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 分页-页面大小
    handleSizeChange(val) {
     this.params.size = val
      this.getDataList()
    },
    // 分页-当前页面
    handleCurrentChange(val) {
      this.params.current = val
      this.getDataList()
    },
    // 子组件新增/更新成功
    subassembly(){
      //关闭全部抽屉
      this.closure()
      //更新数据
      this.getDataList()
    },
    //关闭抽屉
    closure(){
      this.drawer.enable = false;
      this.drawer.add = false;
      this.drawer.update = false;
      this.drawer.details = false;
      this.drawer.data = null
    },
    //抽屉-新增
    drawerAdd(){
      this.closure()
      this.drawer.title = '数据新增'
      this.drawer.enable = true;
      this.drawer.add = true;
    },
    //抽屉-详情
    drawerDetails(data){
      this.closure()
      this.drawer.title = '数据详情'
      this.drawer.enable = true;
      this.drawer.details = true;
      this.drawer.data = data
    },
    //抽屉-更新
    drawerUpdate(data){
      this.closure()
      this.drawer.title = '数据更新'
      this.drawer.enable = true;
      this.drawer.update = true;
      this.drawer.data = data
    }
  }
}
</script>

<style scoped>
.so {
  margin-left: 10px;
  font-size: 14px;
  font-weight: 600;
}
.api {
  width: 100%;
}
</style>
